package com.xfc.web.controller.school;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xfc.common.annotation.Log;
import com.xfc.common.core.controller.BaseController;
import com.xfc.common.core.domain.AjaxResult;
import com.xfc.common.core.page.TableDataInfo;
import com.xfc.common.enums.BusinessType;
import com.xfc.common.utils.poi.ExcelUtil;
import com.xfc.school.domain.ScCourse;
import com.xfc.school.domain.ScCourseList;
import com.xfc.school.domain.ScCourseSchedule;
import com.xfc.school.domain.ScTeacher;
import com.xfc.school.domain.vo.SccCourseVO;
import com.xfc.school.service.IScCourseListService;
import com.xfc.school.service.IScCourseScheduleService;
import com.xfc.school.service.IScCourseService;
import com.xfc.school.service.IScTeacherService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 课程Controller
 * 
 * @author lcj
 * @date 2021-12-09
 */
@Slf4j
@Api(value = "course", tags = "课程管理列表接口")
@RestController
@RequestMapping("/school/sccourse")
public class ScCourseListController extends BaseController
{
    @Autowired
    private IScCourseListService scCourseService;

    @Autowired
    private IScCourseScheduleService courseScheduleService;

    @Autowired
    private IScCourseService courseService;

    @Autowired
    private IScTeacherService teacherService;



    /**
     * 查询课程列表
     */
    @ApiOperation("查询课程列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name="courseName",value="课程名称",dataType = "String"),
    })
    @PreAuthorize("@ss.hasPermi('school:sccourse:list')")
    @GetMapping("/list")
    public AjaxResult list(String courseName) {
        //查询最后日期的课表
        QueryWrapper<ScCourseList> queryWrapper2=new QueryWrapper<>();
        queryWrapper2.eq("course_type",0);
        if (StringUtils.isNotEmpty(courseName)){
            queryWrapper2.like("course_name",courseName);
        }
        queryWrapper2.groupBy("course_name");
        queryWrapper2.select("course_name");
        List<ScCourseList> list = scCourseService.list(queryWrapper2);

        List<SccCourseVO> courseVOS=new ArrayList<>();
        list.forEach(l->{
            QueryWrapper<ScCourseList> queryWrapper3=new QueryWrapper<>();
            queryWrapper3.eq("course_type",0);
            queryWrapper3.eq("course_name",l.getCourseName());
            List<ScCourseList> list1=scCourseService.list(queryWrapper3);
            //查询
            SccCourseVO courseVO=new SccCourseVO();
            courseVO.setCourseName(list1.get(0).getCourseName());
            List<String> monList=new ArrayList<>();
            List<String> tueList=new ArrayList<>();
            List<String> wedList=new ArrayList<>();
            List<String> thuList=new ArrayList<>();
            List<String> friList=new ArrayList<>();
            List<String> satList=new ArrayList<>();
            List<String> sunList=new ArrayList<>();
            list1.forEach(j->{
                if (Objects.nonNull(j.getWeek())){
                    if (j.getWeek()==1){
                        monList.add( DateUtil.format(j.getStartTime(),"HH:mm")+" - "+DateUtil.format(j.getEndTime(),"HH:mm"));
                        courseVO.setMon(monList);
                    }else if (j.getWeek()==2){
                        tueList.add(DateUtil.format(j.getStartTime(),"HH:mm")+" - "+DateUtil.format(j.getEndTime(),"HH:mm"));
                        courseVO.setTue(tueList);
                    }else if (j.getWeek()==3){
                        wedList.add(DateUtil.format(j.getStartTime(),"HH:mm")+" - "+DateUtil.format(j.getEndTime(),"HH:mm"));
                        courseVO.setWed(wedList);
                    }else if (j.getWeek()==4){
                        thuList.add(DateUtil.format(j.getStartTime(),"HH:mm")+" - "+DateUtil.format(j.getEndTime(),"HH:mm"));
                        courseVO.setThu(thuList);
                    }else if (j.getWeek()==5){
                        friList.add(DateUtil.format(j.getStartTime(),"HH:mm")+" - "+DateUtil.format(j.getEndTime(),"HH:mm"));
                        courseVO.setFri(friList);
                    }else if (j.getWeek()==6){
                        satList.add(DateUtil.format(j.getStartTime(),"HH:mm")+" - "+DateUtil.format(j.getEndTime(),"HH:mm"));
                        courseVO.setSat(satList);
                    }else if (j.getWeek()==7){
                        sunList.add(DateUtil.format(j.getStartTime(),"HH:mm")+" - "+DateUtil.format(j.getEndTime(),"HH:mm"));
                        courseVO.setSun(sunList);
                    }
                }
            });
            courseVOS.add(courseVO);

        });
        return AjaxResult.success(courseVOS);
    }

    /**
     * 查询最新课程列表
     */
    @ApiOperation("查询最新课程列表")
    @PreAuthorize("@ss.hasPermi('school:sccourse:list')")
    @GetMapping("/getNewList")
    public TableDataInfo getNewList(@RequestParam String courseName) {
        startPage();
        //查询最后编号
        QueryWrapper<ScCourseList> queryWrapper1=new QueryWrapper<>();
        queryWrapper1.eq("course_type",0);
        queryWrapper1.eq("course_name",courseName);
        List<ScCourseList> list = scCourseService.list(queryWrapper1);
        list.forEach(l->{
            ScTeacher teacher=teacherService.getById(l.getTeacherId());
            if (ObjectUtil.isNotNull(teacher)) {
                l.setTeacherName(teacher.getTeacherName());
                l.setTeacherId(teacher.getTeacherName());
            }
        });
        return getDataTable(list);
    }


    /**
     * 导出课程列表
     */
    @ApiOperation("导出课程列表")
    @PreAuthorize("@ss.hasPermi('school:sccourse:export')")
    @Log(title = "课程", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(ScCourseList scCourse)
    {
        List<ScCourseList> list = scCourseService.list(Wrappers.query(scCourse));
        ExcelUtil<ScCourseList> util = new ExcelUtil<>(ScCourseList.class);
        return util.exportExcel(list, "sccourse");
    }

    /**
     * 获取课程详细信息
     */
    @ApiOperation("获取课程详细信息")
    @PreAuthorize("@ss.hasPermi('school:sccourse:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        ScCourseList scCourse=scCourseService.getById(id);
//        if (Objects.nonNull(scCourse)){
//            ScTeacher teacher=teacherService.getById(scCourse.getTeacherId());
//            if (Objects.nonNull(teacher)){
//                scCourse.setTeacherId(teacher.getTeacherName());
//            }else{
//                scCourse.setTeacherId("暂无");
//            }
//
//        }
        return AjaxResult.success(scCourse);
    }

    /**
     * 新增课程
     */
    @ApiOperation("新增课程")
    @PreAuthorize("@ss.hasPermi('school:sccourse:add')")
    @Log(title = "课程", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ScCourseList scCourse)
    {
        //根据课程id查询课程名称
        ScCourse course=courseService.getById(scCourse.getClassId());
        if (Objects.nonNull(course)){
            scCourse.setCourseName(course.getClassName());
        }
        scCourse.setCourseType(0);
        scCourse.setCreateTime(new Date());
        //判断是否添加成功
        boolean res=scCourseService.save(scCourse);
        //新增课程
        if (res){
            courseScheduleService.addCourseList(scCourse,1);
        }
        return toAjax(res);

    }


    /**
     * 修改课程
     */
    @ApiOperation("修改课程")
    @PreAuthorize("@ss.hasPermi('school:sccourse:edit')")
    @Log(title = "课程", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ScCourseList scCourse)
    {
        //根据课程id查询课程名称
        ScCourse course=courseService.getById(scCourse.getClassId());
        if (Objects.nonNull(course)){
            scCourse.setCourseName(course.getClassName());
        }
        scCourse.setUpdateTime(new Date());
        boolean res=scCourseService.updateById(scCourse);

        //新增课程
        if (res){
            ScCourseList scCourse1=scCourseService.getById(scCourse.getId());
            QueryWrapper<ScCourseSchedule> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("course_list_id",scCourse.getId());
            queryWrapper.ge("start_time",new Date());
            //删除排课
            courseScheduleService.remove(queryWrapper);
            //添加排课
            courseScheduleService.addCourseList(scCourse1,0);
//            //发送通知
//            QueryWrapper<ScCourseSchedule> queryWrapper1=new QueryWrapper<>();
//            queryWrapper1.eq("course_list_id",scCourse.getId());
//            queryWrapper1.ge("start_time",new Date());
//            queryWrapper1.orderByAsc("start_time");
//            queryWrapper1.last("limit 1");
//            ScCourseSchedule scCourseSchedule=courseScheduleService.getOne(queryWrapper);
//            if (Objects.nonNull(scCourseSchedule)){
//                //查询学生信息
//                QueryWrapper<ScBuyCourse> queryWrapper2 = new QueryWrapper<>();
//                queryWrapper2.eq("class_id", scCourseSchedule.getCourseNumber());
//                queryWrapper2.gt("class_surplus_time", 0);
//                List<ScBuyCourse> buyCoursesList = buyCourseService.list(queryWrapper2);
//                List<Map<String,String>> openIdList = new ArrayList<>();
//                buyCoursesList.forEach(j -> {
//                    Map<String,String> map=new HashMap<>(2);
//                    //查询学生信息
//                    ScStudent student = studentService.getById(j.getStudentId());
//                    if (Objects.nonNull(student)) {
//                        ScWxUser user = wxUserService.getOne(new QueryWrapper<ScWxUser>().eq("mobile", student.getStudentMobile()));
//                        //查询openid
//                        map.put("openId",user.getOpenId());
//                        map.put("name",student.getParentName());
//                        openIdList.add(map);
//                    }
//                });
//                //查询课程名称
//                ScCourse course=courseService.getById(scCourseSchedule.getCourseNumber());
//                if (openIdList.size() > 0) {
//                    //发送通知
//                    message.CourseChanage(openIdList, course.getClassName(), DateUtil.format(scCourseSchedule.getStartTime(), "yyyy-MM-dd HH:mm:ss"),DateUtil.format(scCourseSchedule.getEndTime(), "yyyy-MM-dd HH:mm:ss"));
//                } else {
//                    log.error("通知发送失败");
//                }
//
//            }
        }
        return toAjax(res);
    }

    /**
     * 删除课程
     */
    @ApiOperation("删除课程")
    @PreAuthorize("@ss.hasPermi('school:sccourse:remove')")
    @Log(title = "课程", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids){
		List<String> list=new ArrayList<>();
    	if (ids!=null&&ids.length>0) {
            for (String id : ids) {
                list.add(id);
                QueryWrapper<ScCourseSchedule> queryWrapper=new QueryWrapper<>();
                queryWrapper.eq("course_list_id",id);
                queryWrapper.ge("start_time",new Date());
                //删除排课
                courseScheduleService.remove(queryWrapper);
            }
		}

        return toAjax(scCourseService.removeByIds(list));
    }

}
